<?php
namespace Common\Model;

class NewsModel extends Model {
    protected $tableName = 'news';

    public function save2($d) {
        $id     = empty($d['id']) ? 0      : (int)$d['id'];
        $action = $id             ? 'save' : 'add';

        if ($action == 'add') {
            $d['create_time'] = date('Y-m-d H:i:s');
            $d['author']      = C('RUN_LOGIN_USER.name');
        }

        if ($action == 'save') {
            if (!$this->where(['id' => $id])->find()) {
                throw new \Exception('没有找到公告');
            }
        }

        if (empty($d['subject'])) {
            throw new \Exception('请填写标题');
        }

        if ($this->checkExists($d['subject'], $id)) {
            throw new \Exception('此标题已经存在');  
        }

        if (empty($d['text'])) {
            throw new \Exception('请填写内容');
        }

        $d['is_top']  = !isset($d['is_top']) ? 0 : (int)$d['is_top'];
        $d['cate_id'] = empty($d['cate_id']) ? 0 : (int)$d['cate_id'];

        return $this->$action($d);
    }

    /**
     * checkExists
     * 检测公告是否已经存在
     *
     * @param mixed $subject    标题
     * @param mixed $excludeId  需排除的编号
     * @return void
     */
    public function checkExists($subject, $excludeId = null) {
        $id   = (empty($excludeId)) ? 0 : (int)$excludeId;
        $expr = [
            'subject' => $subject,
            'id'      => ['NEQ', $id]
        ];

        return $this->where($expr)->find();
    }

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = 'id DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if(empty($field)) {
            $field = [
                'author'      => 'author',
                'create_date' => 'create_time',
                'is_top'      => 'is_top',
                'subject'     => 'subject',
                'text'        => 'text',
                'cate_id'     => 'cate_id',
            ];
        }

        foreach($field as $k => $v) {
            $tmpExpr = null;
            $val     = isset($d[$k]) ? trim($d[$k]) : '';

            if(strlen($val) < 1) {
                continue;
            }

            switch($k) {
                case 'author' :
                    $expr['author'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'subject' : 
                    $expr['subject'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'text' : 
                    $expr['text'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'create_date' : 
                    $tmpExpr =  "to_char(create_time, 'YYYY-MM-DD') = '{$val}'";
                    break;

                default:
                    $expr[$v] = $d[$k];
            }

            if(!empty($tmpExpr)) {
                $expr['_string'] = empty($expr['_string'])
                                   ? $tmpExpr
                                   : $expr['_string'] . " AND {$tmpExpr}";
            }

            $dao[$k] = $d[$k];
        }

        if(!empty($d['sort']) && in_array($d['sort'], $this->getDbFields())) {
            $sortdir = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';

            $sort        = $d['sort'];
            $dao['sort'] = $sort;

            $sortExpr       = "{$sort} {$sortdir}";
            $dao['sortdir'] = $sortdir;
        }

        $sortExpr = 'is_top DESC,' . $sortExpr;  //让置顶的一直显示在最上面


        return [            
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        ];
    }

    public function del($id) {
        $id   = (int)$id;
        $expr = ['id' => $id];

        if(!$r = $this->where($expr)->find()) {
            return true;
        }

        $this->where($expr)->delete();

        return true;
    }

}
